﻿using System;
using System.Linq.Expressions;
using System.Threading.Tasks;

using Tszy.Unlimited.Data.AdoNet.Sql.Components.Expressions;
using Tszy.Unlimited.Data.AdoNet.Sql.Components.Expressions.Where;

namespace Tszy.Unlimited.Data.AdoNet.Sql.Components.Db.Mysql
{
    /// <summary>
    ///
    /// </summary>
    /// <typeparam name="TSource"></typeparam>
    internal class Cleaner<TSource> : QueryBase<TSource>, ICleaner<TSource>, IWhereCleaner<TSource> where TSource : new()
    {
        private readonly IExecuteCleanerFactory _executeCleanerFactory;

        /// <summary>
        ///
        /// </summary>
        protected static readonly IExpressionExecutor _whereExpressionExecutor = new WhereExpressionExecutor();

        #region 构造器

        /// <summary>
        ///
        /// </summary>
        public Cleaner(IExecuteCleanerFactory executeCleanerFactory) : base()
        {
            _executeCleanerFactory = executeCleanerFactory;

            Context.EntityType = typeof(TSource);
        }

        #endregion 构造器

        #region 条件

        /// <summary>
        ///
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public IWhereCleaner<TSource> Where(Expression<Func<TSource, bool>> predicate)
        {
            var context = Context.Clone();

            _whereExpressionExecutor.Execute(context, predicate);

            return new Cleaner<TSource>(_executeCleanerFactory) { Context = context };
        }

        IWhereCleaner<TSource> IWhereCleaner<TSource>.Where(Expression<Func<TSource, bool>> predicate)
        {
            return Where(predicate);
        }

        #endregion 条件

        #region 执行

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool Execute()
        {
            return _executeCleanerFactory.Create(this).Execute();
            //return new ExecuteCleaner<TSource>(this).Execute();
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ExecuteAsync()
        {
            return await _executeCleanerFactory.Create(this).ExecuteAsync();
            //return await new ExecuteCleaner<TSource>(this).ExecuteAsync();
        }

        #endregion 执行
    }
}